﻿using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.Hangfire;
using Abp.Hangfire.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Runtime.Session;
using AspectCore.Configuration;
using AspectCore.DynamicProxy;
using AspectCore.Extensions.Windsor;
using EasyCaching.Core.Internal;
using EasyCaching.Interceptor.AspectCore;
using Hicap.AuthorizationServer.Core.Common;
using Hicap.AuthorizationServer.Core.Interceptor;
using Hicap.AuthorizationServer.Core.Notify;

namespace Hicap.AuthorizationServer.Core
{
    [DependsOn(typeof(AbpHangfireAspNetCoreModule))]
    public class AuthorizationServerCoreModule : AbpModule
    {
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(AuthorizationServerCoreModule).GetAssembly());
            IocManager.IocContainer.AddAspectCoreFacility(
                c =>
                {
                    c.Interceptors.AddTyped<EasyCachingInterceptor>(method => typeof(IEasyCaching).IsAssignableFrom(method.DeclaringType));
                    c.Interceptors.AddTyped<MethodExecuteLoggerInterceptor>(method =>
                    {
                        bool flag = method.DeclaringType.Assembly.FullName.StartsWith(AuthorizationServerConsts
                            .SysName);

                        if (method.IsConstructor)
                            flag = false;

                        if (method.IsProxy() && method.DeclaringType.IsProxy())
                            flag = false;

                        if (method.DeclaringType.Name.EndsWith("Context"))
                            flag = false;

                        return flag;
                    });
                });
        }

        public override void PreInitialize()
        {
            Configuration.Auditing.IsEnabledForAnonymousUsers = true;
            Configuration.UnitOfWork.OverrideFilter(AbpDataFilters.MustHaveTenant, false);
            Configuration.UnitOfWork.OverrideFilter(AbpDataFilters.MayHaveTenant, false);

            //            IocManager.Register<HicapAuthorizationFilter>(DependencyLifeStyle.Transient);
            //            IocManager.Register<CorsAuthorizationFilter>(DependencyLifeStyle.Transient);
            IocManager.Register<NotifyHub>(DependencyLifeStyle.Singleton);
            Configuration.ReplaceService(typeof(IAbpSession), () =>
            {
                IocManager.Register<IAbpSession, HicapSession>(DependencyLifeStyle.Transient);
            });
            Configuration.ReplaceService(typeof(IPrincipalAccessor), () =>
            {
                IocManager.Register<IPrincipalAccessor, HicapPrincipalAccessor>(DependencyLifeStyle.Transient);
            });
            Configuration.BackgroundJobs.UseHangfire();
        }
    }
}